package fun.qu_an.minecraft.fabric.fzbbl.handle;

import fun.qu_an.minecraft.fabric.fzbbl.FZBBL;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.scoreboard.ScoreboardObjective;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;
import java.util.Map;

public class PistonBrokeBedrockHandle {
	public static void handle(World world, BlockPos bedrockPos) {
		if (world.isClient) return; // 仅服务端

		Map<BlockPos, PlayerEntity> map = FZBBL.PISTON_CACHE.get(world);
		if (map == null) return;

		PlayerEntity player = map.get(bedrockPos);
		block:
		if (player == null) { // 玩家不存在说明是机器破的
			// 日志
			FZBBL.LOGGER.debug("MachineBedrockBroke: {}, {}", world, bedrockPos);

			if (FZBBL.MBB.isEmpty()) break block;

			// 遍历机器破基岩记分板列表
			for (ScoreboardObjective objective : FZBBL.MBB) {
				// 给记分板加分，加分的玩家id等于基岩所在世界($overworld、$the_end、$the_nether)
				world.getScoreboard().getPlayerScore("$" + world.getDimension().getType().toString(), objective).incrementScore();
				world.getScoreboard().getPlayerScore("$total", objective).incrementScore();
			}
		} else {
			// 日志
			FZBBL.LOGGER.debug("BedrockBroke: {}, {}", bedrockPos, player);

			if (FZBBL.BBL.isEmpty()) break block;

			String playerName = player.getEntityName();
			// 遍历玩家破基岩记分板列表
			for (ScoreboardObjective objective : FZBBL.BBL) {
				// 给记分板加分
				world.getScoreboard().getPlayerScore(playerName, objective).incrementScore();
			}
		}

		List<? extends PlayerEntity> players = world.getPlayers();
		if (players.isEmpty()) return; // 该维度没有玩家则直接跳过

		PlayerEntity closestPlayer = getClosestPlayer(world, bedrockPos); // 最大范围 10.5
		if (closestPlayer == null) return;

		// 日志
		FZBBL.LOGGER.debug("LooselyBedrockBroke: {}, {}", bedrockPos, closestPlayer);

		if (FZBBL.LBL.isEmpty()) return;

		String playerName = closestPlayer.getEntityName();
		// 遍历条件宽松的玩家破基岩记分板列表
		// 给最近的玩家加分
		for (ScoreboardObjective objective : FZBBL.LBL) {
			world.getScoreboard().getPlayerScore(playerName, objective).incrementScore();
		}
	}

	@Nullable
	private static PlayerEntity getClosestPlayer(@NotNull World world, @NotNull BlockPos pos) {
		List<? extends PlayerEntity> players = world.getPlayers();
		if (players.isEmpty()) return null;

		double x = pos.getX() + 0.5F;
		double y = pos.getY() + 0.5F;
		double z = pos.getZ() + 0.5F;

		PlayerEntity closestPlayer = null;
		double d = 10.5; // 最大范围 10.5
		for (PlayerEntity player : players) {
			double d2 = getDistance(player, x, y, z);
			if (d2 < d) {
				d = d2;
				closestPlayer = player;
			}
		}

		// 最大范围 10.5 范围内不存在则返回null
		return closestPlayer;
	}

	private static double getDistance(PlayerEntity player, double x, double y, double z) {
		return Math.sqrt(player.squaredDistanceTo(x, y, z));
	}
}
